package com.hcy.app.screen.music.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch

// 歌词行数据类
data class LyricLine(
    val text: String,
    val timestamp: Long, // 毫秒
    val duration: Long = 0L // 持续时间(可选)
) {
    fun isActive(currentPosition: Long): Boolean {
        return currentPosition >= timestamp &&
                (duration == 0L || currentPosition < timestamp + duration)
    }
}

// 歌词解析状态
sealed class LyricsState {
    object Loading : LyricsState()
    data class Success(val lyrics: List<LyricLine>) : LyricsState()
    data class Error(val message: String) : LyricsState()
}

//  LRC 歌词解析器
object LrcParser {
    private val timeRegex = Regex("""$$(\d{2}):(\d{2})\.(\d{1,3})$$(.*)""")

    fun parseLrcContent(content: String): List<LyricLine> {
        val lines = mutableListOf<LyricLine>()
        val timeTextPairs = content.lineSequence()
            .flatMap { parseLrcLine(it) }
            .sortedBy { it.first } // 按时间排序

        // 计算每行持续时间
        timeTextPairs.forEachIndexed { index, (timestamp, text) ->
            val nextTimestamp = timeTextPairs.elementAtOrNull(index + 1)?.first
                ?: (timestamp + 5_000) // 默认最后一行显示5秒
            lines.add(LyricLine(text, timestamp, nextTimestamp - timestamp))
        }

        return lines
    }

    fun parseLrcLine(line: String): List<Pair<Long, String>> {
        if (line.isBlank()) return emptyList()

        val results = mutableListOf<Pair<Long, String>>()
        val matches = timeRegex.findAll(line)

        for (match in matches) {
            val (min, sec, millis, text) = match.destructured

            // 处理毫秒位数（.1 → 100ms, .01 → 10ms, .001 → 1ms）
            val paddedMillis = when (millis.length) {
                1 -> "${millis}00".take(3) // .5 → 500
                2 -> "${millis}0".take(3)  // .71 → 710
                else -> millis.take(3)     // .123 → 123
            }

            val timeMs = min.toLong() * 60_000 +
                    sec.toLong() * 1_000 +
                    paddedMillis.toLong()

            if (text.isNotBlank()) {
                results.add(timeMs to text.trim())
            }
        }

        return results
    }
}

@Composable
fun LyricsDisplay(
    lyricsState: LyricsState,
    currentPosition: Long,
    modifier: Modifier = Modifier,
    onLyricsClick: (Long) -> Unit = {}
) {
    when (lyricsState) {
        LyricsState.Loading -> {
            Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                CircularProgressIndicator()
            }
        }
        is LyricsState.Error -> {
            Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                Text(text = lyricsState.message, color = Color.Red)
            }
        }
        is LyricsState.Success -> {
            val lyrics = lyricsState.lyrics
            val listState = rememberLazyListState()
            val coroutineScope = rememberCoroutineScope()

            // 自动滚动到当前歌词
            LaunchedEffect(currentPosition) {
                val activeIndex = lyrics.indexOfFirst { it.isActive(currentPosition) }
                if (activeIndex >= 0) {
                    coroutineScope.launch {
                        listState.animateScrollToItem(
                            index = activeIndex,
                            scrollOffset = -100 // 稍微提前一点滚动
                        )
                    }
                }
            }

            LazyColumn(
                state = listState,
                modifier = modifier,
                horizontalAlignment = Alignment.CenterHorizontally,
                contentPadding = PaddingValues(vertical = 128.dp) // 上下留白
            ) {
                itemsIndexed(lyrics) { index, line ->
                    val isActive = line.isActive(currentPosition)

                    Text(
                        text = line.text,
                        modifier = Modifier
                            .padding(vertical = 8.dp)
                            .clickable { onLyricsClick(line.timestamp) }
                            .alpha(if (line.text.isBlank()) 0f else 1f),
//                        color = if (isActive) MaterialTheme.colors.primary else MaterialTheme.colors.onSurface.copy(alpha = 0.6f),
                        fontSize = if (isActive) 20.sp else 16.sp,
                        fontWeight = if (isActive) FontWeight.Bold else FontWeight.Normal,
                        textAlign = TextAlign.Center
                    )
                }
            }
        }
    }
}